package com.xiaoy.core.base.security.login.filter;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;


public class ShiroFilter implements Filter {

	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
		
		String username = servletrequest.getParameter("username");
		String password = servletrequest.getParameter("password");
		System.out.println("u-p:"+username + "-" + password);
		
		Subject currentUser = SecurityUtils.getSubject();
		
		if (!currentUser.isAuthenticated() ) {
			
//			if(username==null||"".equals(username)||password==null||"".equals(password)) {
//				
//				
//				
//			}else {
				UsernamePasswordToken token = new UsernamePasswordToken(username,password);
				token.setRememberMe(true);
				currentUser.login(token);
				
				Session session = currentUser.getSession();
				Iterator it = session.getAttributeKeys().iterator();
				
				while (it.hasNext()) {
					String key = it.next().toString();
					System.out.println(key+"-->"+session.getAttribute(key));;
					
				}
				session.setAttribute( "someKey", "aValue" );
//			}
		}
	
		filterchain.doFilter(servletrequest, servletresponse);
		
	}

	@Override
	public void init(FilterConfig filterconfig) throws ServletException {
		
		
	}

}
